/**   
* @Title: GlobalExceptionResolver.java
* @Package org.xaoyaoyao.cloud.web.exception
* @Description: TODO
* @author xaoyaoyao
* @date Feb 11, 2019 3:02:52 PM
* @version V1.0   
*/
package org.xaoyaoyao.cloud.web.exception;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.xaoyaoyao.cloud.common.result.RetCode;
import org.xaoyaoyao.cloud.common.utils.StringUtils;
import org.xaoyaoyao.cloud.web.message.LocaleMessage;
import org.xaoyaoyao.cloud.web.rsp.RspUtils;

import com.fasterxml.jackson.databind.exc.InvalidFormatException;

import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName: GlobalExceptionResolver
 * @Description: TODO
 * @author xaoyaoyao
 * @date Feb 11, 2019 3:02:52 PM
 * 
 */
@Slf4j
@ResponseBody
@ControllerAdvice
public class GlobalExceptionResolver {

	@Autowired
	private LocaleMessage localeMessage;

	@ResponseBody
	@ExceptionHandler(value = Exception.class)
	public Object allExceptionHandler(HttpServletRequest request, Exception ex) throws Exception {
		// TODO
		Locale locale = null;
		log.error(">>>>>>>> URI::{}, Parameters::{}", request.getRequestURI(), request.getParameterMap());
		log.error(ex.getMessage(), ex);
		String msg = null;
		int code = RetCode.SYSERROR;
		if (ex instanceof HttpMessageNotReadableException || ex instanceof InvalidFormatException || ex instanceof ClassCastException) {
			code = RetCode.INVALID_FORMAT_EXCEPTION;
		}
		msg = localeMessage.getMessage(code + "", locale);
		msg = StringUtils.isBlank(msg) ? code == RetCode.INVALID_FORMAT_EXCEPTION ? "请求数据类型不正确！" : "服务异常，请稍后再试！" : msg;
		return RspUtils.makeRsp(code, msg);
	}

}
